package de.karlNet.sambamanager.trees;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.NodeCollapseEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import de.karlNet.sambamanager.ldapController.AbstractLdapTree;
import de.karlNet.sambamanager.ldapModel.LdapObject;
import de.karlNet.sambamanager.view.beans.LdapMemberBean;
import de.karlNet.sambamanager.view.beans.LdapMemberOfBean;
import de.karlNet.sambamanager.view.beans.ManualLeafHandlingTreeNode;
import de.karlNet.sambamanager.view.beans.ViewController;

public abstract class AbstractTreeBean {
	@Autowired
	private ViewController viewController;
	
	@Autowired
	private LdapMemberOfBean ldapMemberOfBean;
	@Autowired
	private LdapMemberBean ldapMemberBean;
	protected TreeNode root;
	protected ManualLeafHandlingTreeNode selectedNode = new ManualLeafHandlingTreeNode(new LdapObject("",""), null);

	protected abstract AbstractLdapTree getLdapTree();
	
	public AbstractTreeBean() {
		super();
	}

	public TreeNode getRoot() {
		return root;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}


	public void onNodeExpand(NodeExpandEvent event) {
		ManualLeafHandlingTreeNode parent = (ManualLeafHandlingTreeNode) event
				.getTreeNode();
		for (LdapObject ldapObject : this.getLdapTree().getChildrenOfDN(parent
				.getLdapObject().getDn())) {
			ManualLeafHandlingTreeNode child = new ManualLeafHandlingTreeNode(
					ldapObject, parent);
		}
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = (ManualLeafHandlingTreeNode) selectedNode;
	
		this.informOtherBeansOfSelect();
	}

	protected void informOtherBeansOfSelect() {
		this.ldapMemberOfBean.setRoot(this.selectedNode);
		this.ldapMemberBean.setRoot(this.selectedNode);
		this.viewController.setTypeToShow(this.selectedNode.getLdapObject());
	}
	
	public void displaySelectedSingle(ActionEvent event) {
		if (selectedNode != null) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Selected", selectedNode.getData().toString());
	
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
	}

	public void onNodeCollapse(NodeCollapseEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Collapsed", event.getTreeNode().toString());
	
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void onNodeSelect(NodeSelectEvent event) {
		this.setSelectedNode(event.getTreeNode());
	}

}